package com.guoyihao.oj.judge;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.guoyihao.oj.common.ErrorCode;
import com.guoyihao.oj.exception.BusinessException;
import com.guoyihao.oj.judge.codesandbox.CodeSandBoxProxy;
import com.guoyihao.oj.judge.strategy.JudgeContext;
import com.guoyihao.oj.model.dto.question.JudgeCase;
import com.guoyihao.oj.model.dto.questionsubmit.JudgeInfo;
import com.guoyihao.oj.model.entity.Question;
import com.guoyihao.oj.model.entity.QuestionSubmit;
import com.guoyihao.oj.model.enums.JudgeInfoMessageEnum;
import com.guoyihao.oj.model.enums.QuestionSubmitStatusEnum;
import com.guoyihao.oj.service.QuestionService;
import com.guoyihao.oj.service.QuestionSubmitService;
import com.guoyihao.oj.judge.codesandbox.CodeSandBox;
import com.guoyihao.oj.judge.codesandbox.CodeSandBoxFactory;
import com.guoyihao.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.guoyihao.oj.judge.codesandbox.model.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class JudgeServiceImpl implements JudgeService{

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private QuestionService questionService;

    @Resource
    private JudgeManager judgeManager;

    private final String TYPE = "remote";


    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1、获取题目
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        //题目为空时
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目信息不存在");
        }
        //2、题目状态不为等待中,就不要重复提交了
        if(!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }
        //3、更改题目为判题中,防止重复执行
        QuestionSubmit questionSubmitResponse = new QuestionSubmit();
        questionSubmitResponse.setId(questionSubmitId);
        questionSubmitResponse.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitResponse);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新成功");
        }
        // 4. 构造代码沙箱所需的参数
        //获取输入测试用例
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCases = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCases.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(questionSubmit.getCode())
                .inputList(inputList)
                .language(questionSubmit.getLanguage())
                .build();
        //5、调用沙箱，获取到执行结果
        ExecuteCodeResponse executeCodeResponse = new CodeSandBoxProxy(CodeSandBoxFactory.newInstance(TYPE)).executeCode(executeCodeRequest);
        log.info("返回的结果：{}",executeCodeResponse.toString());
        //6、根据沙箱的执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = JudgeContext.builder()
                .judgeInfo(executeCodeResponse.getJudgeInfo())
                .inputList(inputList)
                .outputList(executeCodeResponse.getOutputList())
                .judgeCaseList(judgeCases)
                .question(question)
                .questionSubmit(questionSubmit)
                .build();
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        //7、封装数据、返回结果
        questionSubmitResponse.setId(questionSubmitId);
        //如果在执行判题前，代码沙箱发现了错误，即message不为空，则判题失败
        if(!judgeInfo.getMessage().equals(JudgeInfoMessageEnum.ACCEPTED.getValue())){
            questionSubmitResponse.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
        }else{
            questionSubmitResponse.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
            //如果题目通过了,增加通过数量
            question.setAcceptedNum(question.getAcceptedNum() + 1);
            boolean b = questionService.updateById(question);
            if(!b){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
            }
        }
        questionSubmitResponse.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitResponse);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);

        return questionSubmitResult;
    }
}
